<?php

namespace App\Model;

use App\Think\Db;

/**
 * 游戏记录
 */
class GameLog extends BaseModel
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public static function log_list($where=1, $page=1){
        $exec = Db::name('game_log')->where($where)->page("{$page},20")->order("createtime DESC")->cache(60)->select();
        return $exec;
    }

    /**
     * 游戏同步
     */
    public function sync_log($param){
        $platform  = $param['platform'];
        $startTime = $param['startTime'];
        $endTime   = $param['endTime'];
        $log_status = ['api_call'=>true, 'gamelog_sync'=>true, 'raw_sync'=>true, 'logs'=>[]];
        //调用第三方获取源数据
        $cls_name = '\gamesdk\\'.$platform;
        $cls      = new $cls_name();
        $req_param = ['startTime'=>$startTime, 'endTime'=>$endTime, 'account'=>@$param['account']];
        $res = $cls->gameLogSync($req_param);
        if($res['code'] <= 0){
            $log_status['api_call'] = false;
            return $log_status;
        }
        //游戏同步
        $game_log = $res['list'];
        $log_status['logs'] = $game_log;
        if(!self::log_sync($game_log)) $log_status['gamelog_sync'] = false;
        //数据源同步
        $raw_data = $res['raw_data'];
        if(!self::raw_sync($raw_data)) $log_status['raw_sync'] = false;

        /*
        //门槛值统计
        if(!\app\common\model\GameLog::threshold_sync($platform)) $log_status['threshold_sync'] = false;

        //代理佣金结算同步
        if(!\app\common\model\GameLog::comm_sync($game_log)) $log_status['comm_rsync'] = false;
        //代理佣金发放
        if(!\app\common\model\GameLog::comm_settle()) $log_status['comm_settle'] = false;
        //返水奖励发放
        if(!\app\common\model\GameLog::rebate_settle()) $log_status['rebate_settle'] = false;
        */

        log_to(json_encode($req_param)."\n".json_encode($log_status)."\n".json_encode($game_log), "gameSync-{$platform}", '游戏同步');
        return $log_status;
    }



    //游戏记录同步
    public static function log_sync($param){
    	if(count($param) <= 0) return false;
        $users = Db::name('user u')->field('u.id,u.level,u.invite_user_id,u.username,s.*')
            ->join('stats_user s','u.id = s.user_id','LEFT')
            ->where(db_where_in('u.username', array_column($param, 'game_user')))->select();
        $levels    = Db::name('user_level')->select();
        $agents    = Db::name('agent')->field('user_id,parent_id,agent_level,comm_type,comm_rate')->where("status=1")->select();
        $agent_ids = array_column($agents, 'user_id');

    	foreach ($param as $k => $v) {
            $val = $update = [];
            if(!isset($v['game_user']) || empty($v['game_user'])) continue;
            $user_info = arr_row($users, 'username', $v['game_user']);
            $agent_id  = (int)arr_field($users, 'username', $v['game_user'], 'invite_user_id');
            //没有user_id则不同步
            if(!isset($user_info['id']) || $user_info['id'] == 0) continue;

            //状态
            $status = isset($v['status']) ? $v['status'] : "1";
            //输赢
            $money_winlose = isset($v['money_winlose']) ? $v['money_winlose'] : 0.00;
            
            //平台费(用于代理佣金统计)
    		$plat_fee_rate = isset($v['plat_type']) ? platform_name($v['plat_type'],'fee') : 0;
            // $money_plat_fee = $money_winlose<0 ? (-$money_winlose*$plat_fee_rate/100) : ($money_winlose*$plat_fee_rate/100); //0.00;
    		$money_plat_fee = -$money_winlose*$plat_fee_rate/100;
            $val = [
    			'bet_id'        => isset($v['bet_id']) ? $v['bet_id'] : '',
                'user_id'       => @$user_info['id']>0  ? $user_info['id'] : 0,
                'level_id'      => @isset($user_info['level'])  ? $user_info['level'] : 0,
                'agent_id'      => $agent_id>0 ? $agent_id : 0,
    			'game_user'     => isset($v['game_user']) ? $v['game_user'] : "",
    			'plat_type'     => isset($v['plat_type']) ? platform_name($v['plat_type'],'type') : "",
                'plat_key'      => isset($v['plat_type']) ? $v['plat_type'] : "",
                'plat_ext'      => isset($v['plat_ext']) ? $v['plat_ext'] : "",
    			'game_type'     => isset($v['game_type']) ? $v['game_type'] : 0,
    			'game_name'     => isset($v['game_name']) ? $v['game_name'] : "",
    			'money_bet'     => isset($v['money_bet']) ? $v['money_bet'] : 0.00,
    			'money_valid'   => isset($v['money_valid']) ? $v['money_valid'] : 0.00,
    			'money_winlose' => $money_winlose,
                'money_fee'     => isset($v['money_fee']) ? $v['money_fee'] : 0.00,
                'money_plat_fee'=> $money_plat_fee,
    			'status'        => $status,
    			'createtime'    => isset($v['createtime']) ? $v['createtime'] : time(),
                'updatetime'    => isset($v['updatetime']) ? $v['updatetime'] : time()
    		];
            db_replace_row('fa_game_log', $val, ['status'=>$val['status'],'updatetime'=>$val['updatetime'],'money_bet'=>$val['money_bet'],'money_valid'=>$val['money_valid'],'money_winlose'=>$val['money_winlose'],'money_fee'=>$val['money_fee'],'money_plat_fee'=>$val['money_plat_fee'] ]);
            $info = Db::name('game_log')->where("bet_id='{$val['bet_id']}' AND plat_key='{$val['plat_key']}'")->find();

            //提现门槛结算##--- start --- ##//
            if($info['status']==1 && $info['status_threshold']==0){
                $stat = arr_row($users, 'user_id', $val['user_id']);
                if( isset($stat["ts_{$val['plat_type']}"]) && $stat["ts_{$val['plat_type']}"]>0 ){
                    $_stat_data = ['field'=>"ts_{$val['plat_type']}", 'value'=>to_positive($stat["ts_{$val['plat_type']}"]-$val['money_valid'])];
                }else{
                    $_stat_data = ['field'=>"ts_default", 'value'=>to_positive($stat["ts_default"]-$val['money_valid'])];   
                }
                Db::name('stats_user')->where("user_id='{$val['user_id']}'")->update([$_stat_data['field'] => $_stat_data['value']]);
                $update['status_threshold'] = 1;
            }

            //发放(返水)到用户余额##--- start --- ##//
            if($info['status']==1 && $info['status_rebate']==0){
                $platform_list = platform_list();
                $rebate_field = 'rb_'.$val['plat_type'];
                $level_info = arr_row($levels, 'id', $val['level_id']);
                $rate_rebate = isset($level_info[$rebate_field]) ? $level_info[$rebate_field] : 0;
                $money_rebate = $val['money_valid']*$rate_rebate/100;
                // Db::name('user')->where("id='{$val['user_id']}'")->update(['money'=>Db::raw("money+{$money_rebate}")]);
                list($update['money_rebate'],$update['status_rebate']) = [$money_rebate,1];
            }

            //代理佣金结算##--- start --- ##//
            /*
            if($info['status']==1 && $agent_id>0 && $info['money_winlose']<0){
                //普通代理结算
                $agent_info = arr_row($agents, 'user_id', $agent_id);
                $_temp = [
                    'bet_id'        => isset($val['bet_id']) ? $val['bet_id'] : '',
                    'user_id'       => (int)$agent_id,
                    'plat_key'      => isset($val['plat_key']) ? $val['plat_key'] : "",
                    'createtime'    => time(),
                    'updatetime'    => 0,
                ];
                $_temp['agent_level'] = @$agent_info['agent_level'];
                $_temp['comm_rate']   = @$agent_info['comm_rate'];
                $_temp['real_rate']   = @$agent_info['comm_rate'];
                $_temp['comm_money']  = @abs(number_format($val['money_winlose']*$_temp['real_rate']/100, 2));
                db_replace_row('fa_agent_comm', $_temp, ['bet_id'=>$_temp['bet_id']]);
                //上级(高级/总代理)结算
                $parent_agent_id   = in_array($agent_info['parent_id'], $agent_ids) ? $agent_info['parent_id'] : 0;
                $parent_agent_info = arr_row($agents, 'user_id', $agent_info['parent_id']);
                if(!empty($parent_agent_info) && $parent_agent_id>0){
                    $_temp_parent = $_temp;
                    $parent_real_rate = $parent_agent_info['comm_type'] == 0 ? $parent_agent_info['comm_rate'] : $parent_agent_info['comm_rate']-$agent_info['comm_rate'];
                    // foreach($_temp_parent as $k=>$v) if($k == 'user_id') $_temp_parent['user_id'] = @$parent_agent_id;
                    $_temp_parent['user_id']     = $parent_agent_id;
                    $_temp_parent['agent_level'] = $parent_agent_info['agent_level'];
                    $_temp_parent['comm_rate']   = $parent_agent_info['comm_rate'];
                    $_temp_parent['real_rate']   = $parent_real_rate;
                    $_temp_parent['comm_money']  = @abs(number_format($val['money_winlose']*$_temp_parent['real_rate']/100, 2));
                    if($_temp_parent['comm_money']>0) $_temp_parent;
                    db_replace_row('fa_agent_comm', $_temp_parent, ['bet_id'=>$_temp['bet_id']]);
                }
            }*/

            //更新记录
            Db::name('game_log')->where("bet_id='{$val['bet_id']}' AND plat_key='{$val['plat_key']}'")->update($update);
    	}
    	return true;
    }

    //游戏数据源同步
    public static function raw_sync($param){
        if(count($param) <= 0) return false;
        $users = Db::name('user u')->field('u.id,u.level,u.invite_user_id,u.username,s.*')
            ->join('stats_user s','u.id = s.user_id','LEFT')
            ->where(db_where_in('u.username', array_column($param, 'game_user')))->select();
        $insert_arr = [];
        foreach ($param as $k => $v) {
            $val = [];
            if(!isset($v['game_user']) || empty($v['game_user'])) continue;
            $user_info = arr_row($users, 'username', $v['game_user']);
            //没有user_id则不同步
            if(!isset($user_info['id']) || $user_info['id'] == 0) continue;
            $val = [
                'plat_type'  => sprintf("'%s'", platform_name($v['plat_type'],'type')),
                'plat_key'   => sprintf("'%s'", $v['plat_type']),
                'plat_ext'   => isset($v['plat_ext']) ? "'{$v['plat_ext']}'" : "''",
                'bet_id'     => "'{$v['bet_id']}'",
                'data_json'  => "'".json_encode($v)."'",
                'createtime' => time(),
                'updatetime' => $v['updatetime']
            ];
            $insert_arr[] = $val;
        }
        if(db_replace_all('fa_raw_data', $insert_arr, ['data_json','updatetime'])) return true;
        return true;
    }


    /**
     * 发放佣金到代理余额
     */
    public static function comm_settle($month){
        $res = Db::name('stats_agent_month')->field('month,user_id,user_comm,agent_comm,total_comm,trim_comm,status_comm')->where("month='{$month}'")->select();
        foreach ($res as $k => $v) {
            if($v['status_comm'] == 1 || $v['total_comm']<=0) continue;
            unset($v['status_comm']);
            $v['createtime'] = time();
            
            $insertId = Db::name('agent_comm')->insertGetId($v);
            if($insertId>0){
                $update_money = $v['total_comm']+$v['trim_comm'];
                Db::name('agent')->where("user_id='{$v['user_id']}'")->update([ 'money'=>Db::raw("money+{$update_money}") ]);
                Db::name('stats_agent_month')->where("month='{$month}' AND user_id='{$v['user_id']}'")->update(['status_comm'=>1]);
            }
            
        }
        return true;
    }

}
